import { useCallback, useState } from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

interface UsePdfExportOptions {
  filename?: string;
  quality?: number;
  scale?: number;
  useCORS?: boolean;
  allowTaint?: boolean;
}

interface UsePdfExportReturn {
  exportToPdf: (selector?: string) => Promise<void>;
  isExporting: boolean;
  error: string | null;
}

export const usePdfExport = (options: UsePdfExportOptions = {}): UsePdfExportReturn => {
  const [isExporting, setIsExporting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { filename = 'resume.pdf', quality = 1, scale = 2, useCORS = true, allowTaint = true } = options;

  const exportToPdf = useCallback(
    async (selector: string = '.resume-container') => {
      try {
        setIsExporting(true);
        setError(null);

        // 查找目标元素
        const element = document.querySelector(selector) as HTMLElement;
        if (!element) {
          throw new Error(`找不到选择器 "${selector}" 对应的元素`);
        }

        // 使用 html2canvas 将元素转换为 canvas
        const canvas = await html2canvas(element, {
          scale,
          useCORS,
          allowTaint,
          backgroundColor: '#ffffff',
          logging: false,
          width: element.scrollWidth,
          height: element.scrollHeight,
        });

        // 获取 canvas 的尺寸
        const imgWidth = canvas.width;
        const imgHeight = canvas.height;

        // 创建 PDF 文档
        // 计算 PDF 页面尺寸 (A4宽度: 210 mm，高度可以扩展)
        const pdfWidth = 210;
        const pdfHeight = (imgHeight * pdfWidth) / imgWidth;

        // 设置最大页面高度限制 (可以根据需要调整，这里设置为A4高度的3倍)
        const maxPageHeight = 297 * 3; // 最大页面高度 (mm)
        const finalPdfHeight = Math.min(pdfHeight, maxPageHeight);

        const pdf = new jsPDF({
          orientation: 'portrait',
          unit: 'mm',
          format: [pdfWidth, finalPdfHeight], // 使用自定义页面尺寸
        });

        // 将 canvas 转换为图片数据
        const imgData = canvas.toDataURL('image/png', quality);

        // 如果内容高度超过设定的最大页面高度，需要分页处理
        const pageHeight = finalPdfHeight; // 使用计算出的页面高度

        if (pdfHeight <= pageHeight) {
          // 内容不超过一页，直接添加
          pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight, undefined, 'FAST');
        } else {
          // 内容超过一页，需要智能分页
          const pixelsPerMM = imgHeight / pdfHeight; // 像素到毫米的转换比例
          const pageHeightInPixels = pageHeight * pixelsPerMM;

          let currentY = 0;
          let pageIndex = 0;

          while (currentY < imgHeight) {
            if (pageIndex > 0) {
              pdf.addPage();
            }

            // 计算当前页面应该显示的高度
            const remainingHeight = imgHeight - currentY;
            const currentPageHeightInPixels = Math.min(pageHeightInPixels, remainingHeight);
            const currentPageHeightInMM = currentPageHeightInPixels / pixelsPerMM;

            // 创建当前页面的canvas片段
            const pageCanvas = document.createElement('canvas');
            const pageCtx = pageCanvas.getContext('2d')!;
            pageCanvas.width = canvas.width;
            pageCanvas.height = currentPageHeightInPixels;

            // 绘制当前页面的内容
            pageCtx.drawImage(
              canvas,
              0,
              currentY, // 源图像的起始位置
              canvas.width,
              currentPageHeightInPixels, // 源图像的尺寸
              0,
              0, // 目标位置
              canvas.width,
              currentPageHeightInPixels // 目标尺寸
            );

            // 将页面片段转换为图片并添加到PDF
            const pageImgData = pageCanvas.toDataURL('image/png', quality);
            pdf.addImage(pageImgData, 'PNG', 0, 0, pdfWidth, currentPageHeightInMM, undefined, 'FAST');

            currentY += currentPageHeightInPixels;
            pageIndex++;
          }
        }

        // 保存 PDF
        pdf.save(filename);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '导出PDF时发生未知错误';
        setError(errorMessage);
        console.error('PDF导出失败:', err);
      } finally {
        setIsExporting(false);
      }
    },
    [filename, quality, scale, useCORS, allowTaint]
  );

  return {
    exportToPdf,
    isExporting,
    error,
  };
};
